package com.sfang.common.extension;

import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

@RestController
@ConditionalOnProperty(
        name = {"spring.cloud.nacos.discovery.register-enabled"},
        havingValue = "false",
        matchIfMissing = false
)
public class CustomNacosDiscovery implements CommandLineRunner {
    @Autowired
    NacosServiceRegistry nacosServiceRegistry;
    @Autowired
    NacosRegistration nacosRegistration;
    @Autowired
    Environment environment;
    private static Logger LOGGER = LoggerFactory.getLogger(CustomNacosDiscovery.class);

    @Override
    public void run(String... args) throws Exception {
        nacosRegistration.setPort(Integer.valueOf(environment.getProperty("server.port")));
        registerAsync();
    }

    @RequestMapping("/nacos/register")
    public String register() {
        nacosServiceRegistry.register(nacosRegistration);
        LOGGER.info("customNacosDiscovery nacosServiceRegistry register success");
        JSONObject resp = new JSONObject();
        resp.put("code", 200);
        return resp.toJSONString();
    }

    @RequestMapping("/nacos/deregister")
    public String deregister() {
        nacosServiceRegistry.deregister(nacosRegistration);
        LOGGER.info("customNacosDiscovery nacosServiceRegistry deregister success");
        JSONObject resp = new JSONObject();
        resp.put("code", 200);
        return resp.toJSONString();
    }

    private void registerAsync(){
        CompletableFuture.runAsync(() -> {

            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            nacosServiceRegistry.register(nacosRegistration);
            LOGGER.info("customNacosDiscovery nacosServiceRegistry register success");
        });
    }
}
